package Controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import POJO.Category;
import Service.AdminService;
import Service.HomeService;

@Controller
@Scope("request")
public class AdminController {
	@Autowired
	private AdminService adminService;

	@Autowired
	private HomeService homeService;

	@Autowired
	private POJO.Cart cart;
	
	@RequestMapping("admin/admin")
	public ModelAndView showInfo()
	{
		System.out.println("======admin======" +cart.getCartDetails().size());
		return new ModelAndView("admin");
	}

	@RequestMapping("admin/category")
	public ModelAndView showCategory(@ModelAttribute("command") Category category) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("newmodel", homeService.createTreeMenu());
		model.put("category", adminService.getCategoryById(category.getCategoryId()));
		model.put("categoryParent", adminService.getCategoryById(adminService
				.getCategoryById(category.getCategoryId()).getParentId()));
		model.put("categories", adminService.getListCategory());
		//System.out.println("Id  " + category.getCategoryId());
		return new ModelAndView("category", model);
	}

	@RequestMapping(value="admin/saveCategory", method = RequestMethod.POST)
	public ModelAndView saveCategory(@ModelAttribute("command") Category category, 
			BindingResult result) {
		adminService.saveCategory(category);
		//System.out.println("Id  " + category.getCategoryId());
		return new ModelAndView("redirect:/admin/category.html?categoryId=" + category.getCategoryId());
	}
	
	@RequestMapping(value = "admin/addCategory", method = RequestMethod.POST)
	public ModelAndView addCategory(@ModelAttribute("command") Category category,
			BindingResult result) {

		adminService.addCategory(category);
		
		return new ModelAndView("redirect:/admin/category.html?categoryId=" + category.getCategoryId());
	}
	
	@RequestMapping(value = "admin/deleteCategory", method = RequestMethod.GET)
	public ModelAndView deleteCategory(@ModelAttribute("command") Category category,
			BindingResult result) {
		
		adminService.deleteCategory(category);		

		return new ModelAndView("redirect:/admin/category.html?categoryId=0");
	}
	
	
}
